<template>
  <div class="page_content">
    <div v-if="isPageLoading" class="page_loading fixed">
      <van-loading size="24px" vertical color="#fff">加载中...</van-loading>
    </div>
    <header>
      <van-nav-bar class="main_header" title="国际跆拳道级段位信息">
        <template #left>
          <span @click="goBack">返回</span>
        </template>
        <template #right>
          <span @click="submitRefresh">确定</span>
        </template>
      </van-nav-bar>
    </header>
    <div class="main_content">
      <van-form ref="vo" label-width="85px" label-align="left" :scroll-to-error="true">
        <van-field
          name="wtaBeltLevel"
          label="国际段位"
          placeholder="请选择国际段位"
          right-icon="arrow"
          :value="findDictDataByCode('dictWtaBeltLevel', vo.wtaBeltLevel).value"
          :rules="ModTkwIntDanVO_Rules.wtaBeltLevel"
          @click="openSelectBox('wtaBeltLevel')"
        />
        <van-field
          v-model.trim="vo.wtaBeltId"
          label="国际段位编号"
          name="wtaBeltId"
          :required="!vo.wtaBeltLevel ? false : true"
          clearable
          :rules="!vo.wtaBeltLevel ? [] : ModTkwIntDanVO_Rules.wtaBeltId"
        />
        <van-field
          v-model.trim="vo.wtaBeltName"
          label="国际段位证书姓名（英文）"
          name="ctaBeltLevelId"
          :required="!vo.wtaBeltLevel ? false : true"
          clearable
          :rules="!vo.wtaBeltLevel ? [] : ModTkwIntDanVO_Rules.wtaBeltName"
        />
        <van-field
          label="国际段位照片"
          name="ctaBeltLevelImageUrl1"
          :required="!vo.wtaBeltLevel ? false : true"
          input-align="right"
          right-icon="arrow"
          :style="{ 'line-height': vo.wtaBeltImageUrl1 ? '50px' : '24px' }"
          :rules="!vo.wtaBeltLevel ? [] : ModTkwIntDanVO_Rules.wtaBeltImageUrl1"
          @click="openChangeImg()"
        >
          <template #input>
            <div v-for="(item, index) in 6" :key="index">
              <van-image
                width="25"
                height="25"
                class="gl_mr_5"
                :rules="!vo.wtaBeltLevel ? [] : ModTkwIntDanVO_Rules.wtaBeltImageUrl1"
                :src="getStaticFileUrl(imgList[index])"
                @click="imagePreview(imgList[index])"
              />
            </div>
          </template>
        </van-field>
        <!-- 头像 -->
        <van-popup
          v-model="logoDialog"
          get-container="#app"
          position="right"
          :style="{ width: '100%', height: '100%' }"
        >
          <van-nav-bar>
            <template #left>
              <span @click="logoDialog = false">返回</span>
            </template>
          </van-nav-bar>
          <div class="gl_clear">
            <div v-for="(item, index) in 6" :key="index" class="gl_my_10" align="center" style="position:relative;">
              <upload-file
                :ref="'refImg' + index"
                :action="baseUrl + '/api/upload/image'"
                accept=".jpg,.png,.jpeg"
                class-name="wtaImg"
                :file-url="getStaticFileUrl(imgList[index], 'imgList')"
                @uploadSuccess="photoSavePositive($event, 'imgList', index)"
              >
                <span slot="uploadName" style="font-size: 14px;">点击上传照片</span>
              </upload-file>
              <div class="imgDelWrap" @click="delImg(index)">
                <i class="imgDelete el-icon-delete" />
              </div>
            </div>
          </div>
        </van-popup>
        <!-- 下拉选择 -->
        <popup-select
          ref="popupSelect"
          :select-data="selectData"
          :default-code="selectDefaultCode"
          :value-key="valueKey"
          @onConfirm="confirmSelectBox"
        />
      </van-form>
    </div>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
import { CopyData } from '@/lib';
import UploadFile from '@/viewMobile/components/UploadFile/index';
import PopupSelect from '@/viewMobile/components/PopupSelect';
import { ModTkwChiDanVO } from '@/lib/form/train/enter.js';
import { ModTkwIntDanVO_Rules } from '@/lib/validate/mobile/myCenter';
import {
  api_GET_EventsManagementRegisterId,
  api_PUT_EventsManagementRegisterId,
  api_POST_EventsManagementRegister
} from '@/extend/api/gameswaggerApi/app';
export default {
  components: {
    UploadFile,
    PopupSelect
  },
  data() {
    return {
      isPageLoading: false,
      individualInfo: {},
      createRegisterInput: null,
      vo: new ModTkwChiDanVO(),
      ModTkwIntDanVO_Rules: new ModTkwIntDanVO_Rules(),
      /* 上传照片相关 */
      baseUrl: WEB_CONFIG.VUE_APP_STATIC_FILE_RUL,
      logoDialog: false,
      memberImgDialog: false,
      imgList: [],
      // 选择器
      selectData: [],
      selectDefaultCode: null,
      valueKey: 'value',
      defaultArea: [],
      defaultDateTime: '',
      popupDateTime: false
    };
  },
  computed: {
    ...mapState({
      currentUserType: state => state.user.currentUserType,
      dict: state => state.dict,
      cache: state => state.dict.cache
    })
  },
  watch: {
    currentUserType: {
      handler(val) {
        if (!val) return;
        this.getIndividualInfo();
      }
    }
  },
  created() {
    this.getDict();
    this.gameId = this.$route.params.id;
    if (this.currentUserType) {
      this.getIndividualInfo();
    }
  },
  methods: {
    ...mapActions({ getDict: 'dict/getDict' }),
    // 获取个人数据
    getIndividualInfo() {
      if (!this.currentUserType.registerId) return;
      api_GET_EventsManagementRegisterId(
        this.currentUserType.registerId,
        { IncludeGender: true, IncludeIdCardType: true }
      ).then(res => {
        this.individualInfo = res;
        this.vo = res;
        this.formatImgListFromMemberImg(res);
        this.$store.dispatch('user/getSaveCurrentUserIndInfo', res);
      }, error => {
        this.$toast.fail(`获取个人信息失败！${error.error.message}`);
      });
    },
    submitRefresh() {
      this.createRegisterInput = JSON.parse(JSON.stringify(this.individualInfo));
      CopyData(this.vo, this.createRegisterInput);
      this.getUserImgData();
      if (this.validateRule()) {
        if (this.currentUserType.registerId) {
          this.updateMemberInfo();
        } else {
          this.addMemberInfo();
        }
      }
    },
    // 校验规则
    validateRule() {
      // 判断级位或段位有值时，对应的编号和照片是否为空
      if (this.createRegisterInput.wtaBeltLevel) {
        if (!this.createRegisterInput.wtaBeltId || this.createRegisterInput.wtaBeltId === '') {
          this.$toast.fail('国际段位编号不能为空');
          return false;
        }
        if (!this.createRegisterInput.wtaBeltName || this.createRegisterInput.wtaBeltName === '') {
          this.$toast.fail('国际段位证书姓名（英文）不能为空');
          return false;
        } else if (!(/^[A-Za-z]*(\s[A-Za-z]*)*$/).test(this.createRegisterInput.wtaBeltName)) {
          this.$toast.fail('国际段位证书姓名（英文）格式不正确');
          return false;
        }
        if (!this.createRegisterInput.wtaBeltImageUrl1 || this.createRegisterInput.wtaBeltImageUrl1 === '') {
          this.$toast.fail('国际跆协段位照片不能为空');
          return false;
        }
      }
      return true;
    },
    // 新增个人信息
    addMemberInfo() {
      // 将空字符串转为Null
      for (const k in this.createRegisterInput) {
        const ktem = this.createRegisterInput[k];
        if (ktem === '') {
          this.createRegisterInput[k] = null;
        }
      }
      api_POST_EventsManagementRegister(this.createRegisterInput).then(() => {
        this.isPageLoading = false;
        this.dialogVisible = false;
        this.getIndividualInfo();
        this.$store.dispatch('user/getInfo');
        this.$store.dispatch('user/getCurrentUserType');
        this.$toast.success('操作成功');
      }, error => {
        this.$toast.fail(`${error.error.message}`);
        this.isPageLoading = false;
      });
    },
    // 更新个人信息
    updateMemberInfo() {
      api_PUT_EventsManagementRegisterId(this.currentUserType.registerId, this.createRegisterInput).then(() => {
        this.isPageLoading = false;
        this.dialogVisible = false;
        this.getIndividualInfo();
        this.$toast.success('操作成功');
      }, error => {
        this.$toast.fail(`${error.error.message}`);
        this.isPageLoading = false;
      });
    },
    // 打开修改照片
    openChangeImg() {
      this.logoDialog = true;
    },
    photoSavePositive(fileUrl, type, index) {
      const _data = this[type];
      this.$set(_data, index, fileUrl.tempUrl);
    },
    delImg(index) {
      this.imgList.splice(index, 1);
      for (let i = index; i < 6; i++) {
        this.$refs['refImg' + i][0].init(this.imgList[i]);
      }
    },
    /* ===== select 选择器相关 ===== */
    openSelectBox(code) {
      // 解决某种情况下弹出框非本系统操作关闭之后无法打开
      this.$refs.popupSelect.close();
      this.selectBoxCode = code;
      this.valueKey = 'value';
      this.selectDefaultCode = String(this.vo[code]);
      this.selectData = this.dict ? this.dict.dictWtaBeltLevel : [];
      this.$refs.popupSelect.open();
    },
    confirmSelectBox(value) {
      this.vo[this.selectBoxCode] = value.code;
    },
    // 根据code在相应字典中寻找数据
    findDictDataByCode (dictKey, code) {
      const _dict = this.dict[dictKey];
      if (_dict) {
        return _dict.find(item => item.code === code) || {};
      } else {
        console.log('findDictDataByCode -> findDictDataByCode: ' + dictKey + ', 未找到字典数据.');
        return {};
      }
    },
    // 根据数据格式化图片数组
    formatImgListFromMemberImg (data) {
      const _keyList = [
        'wtaBeltImageUrl1',
        'wtaBeltImageUrl2',
        'wtaBeltImageUrl3',
        'wtaBeltImageUrl4',
        'wtaBeltImageUrl5',
        'wtaBeltImageUrl6'
      ];

      const _imgList = [];

      for (let i = 0; i < _keyList.length; i++) {
        const item = _keyList[i];
        if (data[item]) {
          _imgList.push(data[item]);
          this.vo[item] = '';
        }
      }
      this.imgList = _imgList;
    },
    // 外部获取组件数据的方法
    getUserImgData () {
      for (let i = 0; i < this.imgList.length; i++) {
        const item = this.imgList[i];
        this.createRegisterInput['wtaBeltImageUrl' + (i + 1)] = item;
      }
    },
    // 图片预览
    imagePreview(relativeUrl) {
      this.$imagePreview([this.getStaticFileUrl(relativeUrl)]);
      event.stopPropagation();
    },
    // 获取静态文件
    getStaticFileUrl(relativeUrl, code) {
      if (relativeUrl) {
        return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
      } else {
        return code ? '' : require('@/assets/images/face_default.png');
      }
    },
    goBack() {
      this.$router.push({
        path: `/myCenter${this.gameId && '/' + this.gameId || ''}/individual`
      });
    }
  }
};
</script>
<style>
.wtaImg {
  width: 180px;
  height: 88px;
}
.imgDelWrap {
  position: absolute;
  top: -29px;
  right: 70px;
  width: 60px;
  height: 60px;
  cursor: pointer;
  transform: rotate(45deg);
}
.imgDelete {
  font-size: 18px;
  position: absolute;
  top: 37px;
  left: 21px;
  transform: rotate(-45deg);
  color: rgba(255, 0, 0, 0.8);
}
</style>

